package com.tbit.uqbike.client.controller;

import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.UserOpLog;
import com.tbit.uqbike.client.business.user_op_log.service.UserOpLogService;
import com.tbit.uqbike.client.constant.MapConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.Machine;
import com.tbit.uqbike.client.pojo.Suggestion;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.GeoService;
import com.tbit.uqbike.client.service.MachineService;
import com.tbit.uqbike.client.service.SuggestionService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.EmojiCheckUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 建议反馈
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Slf4j
@Controller
@RequestMapping("/suggestion")
public class SuggestionController {
    @Autowired
    private SuggestionService suggestionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private GeoService geoService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private UserOpLogService userOpLogService;

    /**
     * 提交意见
     *
     * @param token      令牌
     * @param lo         经度
     * @param mapType    地图类型
     * @param la         纬度
     * @param suggestion 建议类
     * @param session    会话
     * @param response   响应
     * @ignoreParams request
     */
    @RequestMapping("/add")
    public void add(String token, Double lo, Integer mapType, Double la, Suggestion suggestion,
                    HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = tokenService.getUser(token);
            if (Objects.isNull(suggestion)) {
                log.error("suggestion 对象不能为空");
                return ;
            }
            /* 校验 */
            Assert.hasLength(suggestion.getTitle(), "-60001", "标题不能为空");
            Assert.notNull(suggestion.getAccountId(), "-10001", "品牌id不能为空");
            Assert.hasLength(suggestion.getContent(), "-60002", "内容不能为空");
            Assert.notNull(lo, "-2001", "经度不能为空");
            Assert.notNull(la, "-2002", "纬度不能为空");
            EmojiCheckUtil.check(suggestion.getContent());
            EmojiCheckUtil.check(suggestion.getTitle());
            EmojiCheckUtil.check(suggestion.getRemark());
            if (mapType == null) {
                mapType = MapConstant.MAP_GOOGLE;
            }
            Integer agentId = geoService.getBelongAccount(suggestion.getAccountId(), lo, la, mapType);
            if (agentId == null) {
                throw new BaseException("-3050", "运营区域外,请在运营区域内使用");
            }
            suggestion.setAccountId(agentId);
            // （意见反馈）根据车辆id获取区域id，填充区域id
            if (Objects.nonNull(suggestion.getUserCode())){
                // 车辆编号
                String userCode = suggestion.getUserCode();
                Machine machine = machineService.getByUserCode(userCode);
                suggestion.setAccountId(machine.getAccountId());
            }

            suggestion.setUserId(user.getUserId());
            suggestion.setAddTime(DateTimeUtil.getNowTime());

            List<MultipartFile> list = new ArrayList<>();
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                /* 得到所有的文件 */
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    list.add(file);
                }
            }
            suggestionService.insert(suggestion, list,lo,la);

            // 插入用户操作日志
            userOpLogService.insertSingle(UserOpLog.builder()
                    .accountId(user.getAccountId())
                    .opUser(user.getName())
                    .opUserPhone(user.getPhone())
                    .targetUser(user.getName())
                    .targetUserPhone(user.getPhone())
                    .operation("意见反馈")
                    .opPlatform(OperationPlatform.CLIENT.code)
                    .opTime(LocalDateTime.now())
                    .result(true)
                    .build());

            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

    /**
     * 获取用户意见反馈历史分页
     *
     * @param token
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/getSuggest")
    public void getSuggest(String token, Integer rowCount, Integer pageNO, HttpSession session,
                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            User user = tokenService.getUser(token);
            List<Suggestion> list = suggestionService.queryPage(user.getUserId(), pageNO, rowCount);
            Integer count = suggestionService.queryCount(user.getUserId());
            map.put("total", count);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, list);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

}